﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Controller;
using Entity;
using iTextSharp.text;
using ListItem = System.Web.UI.WebControls.ListItem;

namespace Web
{
    public partial class MakeVendorPO : System.Web.UI.Page
    {
        Helper helper = new Helper();
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                Session["VendorPoItemEntities"] = null;
                
                //get skyfab address
                CompanyController companyController=new CompanyController();
                CompanyEntity companyEntity = companyController.FindCompany();
                string[] address = companyEntity.Address.Split(',');
                if(address.Length==3)
                {
                    ShipToTextBox1.Text = address[0];
                    ShipToTextBox2.Text = address[1];
                    ShipToTextBox3.Text = address[2];
                }
                if (address.Length == 2)
                {
                    ShipToTextBox1.Text = address[0];
                    ShipToTextBox2.Text = address[1];
                }
                if(address.Length==1)
                {
                    ShipToTextBox1.Text = address[0];
                }
                ZipCodeTextBox.Text = companyEntity.ZipCode;

                //bind vendor
                VendorController sc = new VendorController();
                IList<VendorEntity> vendorEntities = sc.FindAllVendorEntities();
                SupplierDropDownList.DataSource = vendorEntities;
                SupplierDropDownList.DataTextField = "ShortName";
                SupplierDropDownList.DataValueField = "Id";
                SupplierDropDownList.DataBind();

                this.GenreatePONo();
                //set all date textbox as today
                //PODateTextBox_CalendarExtender.SelectedDate = System.DateTime.Now;
                RequestDateTextBox_CalendarExtender.SelectedDate = System.DateTime.Now;

                //bind products
                ProductController productController = new ProductController();
                IList<ProductEntity> productEntities = productController.FindAllProductEntities();
                ProductDropDownList.DataSource = productEntities;
                ProductDropDownList.DataTextField = "ProductNoAndRevision";
                ProductDropDownList.DataValueField = "Id";
                ProductDropDownList.DataBind();
                ProductDropDownList.Items.Insert(0, new ListItem("--Select Product--", "0"));



                //VendorPOItemGridView.DataSource = Session["VendorPoItemEntities"] as IList<VendorPOItemEntity>;
                //VendorPOItemGridView.DataBind();
                IList<VendorPOItemEntity> vendorPoItemEntities=new List<VendorPOItemEntity>();
                double total = 0;
                if (Session["VendorPoItemEntities"] != null)
                {
                    vendorPoItemEntities = Session["VendorPoItemEntities"] as IList<VendorPOItemEntity>;
                    VendorPOItemGridView.DataSource = vendorPoItemEntities;
                    VendorPOItemGridView.DataBind();
                    
                    //foreach (VendorPOItemEntity v in vendorPoItemEntities)
                    //{
                    //    total = total + (double)(v.RequestQty*v.Price);

                    //}
                    
                }
                foreach (GridViewRow r in VendorPOItemGridView.Rows)
                {
                    TextBox qtyTextBox = (TextBox)r.Cells[4].FindControl("vQtyTextBox");
                    TextBox priceTextBox=(TextBox)r.Cells[5].FindControl("vPriceTextBox");
                    double qty = Convert.ToDouble(qtyTextBox.Text.Trim());
                    double price = Convert.ToDouble(priceTextBox.Text.Trim());
                    total = total + qty*price;
                }
                
                TotalLabel.Text = total.ToString() + " SGD";

            }
            this.PreRender += new EventHandler(UpdateFlashMessage);
        }

        private void UpdateFlashMessage(object sender, EventArgs e)
        {
            helper.ShowFlashMessage(FlashMessageLabel);
        }

        protected void SupplierDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            this.GenreatePONo();
        }

        public void GenreatePONo()
        {
            //Genreate the po no
            VendorPOController vendorPoController = new VendorPOController();
            int newPONumber = vendorPoController.FindLargestVendorPoNumber() + 1;
            
            int vendorId = Convert.ToInt32(SupplierDropDownList.SelectedValue);
            
            VendorController vendorController = new VendorController();
            VendorEntity vendorEntity = vendorController.findVendorByVendorId(vendorId);
            PONumberTextBox.Text = "P" + vendorEntity.Code + "-" + newPONumber;
        }

        protected void ProductDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ProductDropDownList.SelectedIndex != 0)
            {
                int productId = Convert.ToInt32(ProductDropDownList.SelectedValue);
                ProductController productController = new ProductController();
                ProductEntity productEntity = productController.FindProductById(productId);
                ProductNameLabel.Text = productEntity.Name;
            }
            else
            {
                ProductNameLabel.Text = "";
            }

        }
        IList<VendorPOItemEntity> vendorPoItemEntities = new List<VendorPOItemEntity>();
        protected void InsertButton_Click(object sender, EventArgs e)
        {
            if (Session["VendorPoItemEntities"] == null&&ProductDropDownList.SelectedIndex!=0)
            {
                VendorPOItemEntity vendorPOItemEntity = new VendorPOItemEntity();
                ProductController productController = new ProductController();
                ProductEntity productEntity =
                    productController.FindProductById(Convert.ToInt32(ProductDropDownList.SelectedValue));


                vendorPOItemEntity.ProductId = productEntity.Id;
                vendorPOItemEntity.ProductName = productEntity.Name;
                vendorPOItemEntity.ProductNo = productEntity.No;
                vendorPOItemEntity.Rev = productEntity.Revision;
                vendorPOItemEntity.RequestDate = Convert.ToDateTime(RequestDateTextBox.Text);
                vendorPOItemEntity.RequestQty = Convert.ToInt32(QtyTextBox.Text);
                vendorPOItemEntity.Lot = Convert.ToInt32(LotTextBox.Text);
                vendorPOItemEntity.Price = Convert.ToDecimal(PriceTextBox.Text);
                vendorPOItemEntity.Amount = vendorPOItemEntity.Price * vendorPOItemEntity.RequestQty;
                vendorPOItemEntity.VendorId =Convert.ToInt32(SupplierDropDownList.SelectedValue);
                vendorPOItemEntity.FormatDate = vendorPOItemEntity.RequestDate.ToString("d MMM, yyyy");
                vendorPOItemEntity.ItemCategory = productEntity.CategoryName;
                vendorPoItemEntities.Add(vendorPOItemEntity);
                
            }
            else
            {
                if (ProductDropDownList.SelectedIndex != 0)
                {
                    vendorPoItemEntities = Session["VendorPoItemEntities"] as IList<VendorPOItemEntity>;
                    VendorPOItemEntity vendorPOItemEntity = new VendorPOItemEntity();
                    ProductController productController = new ProductController();
                    ProductEntity productEntity =
                        productController.FindProductById(Convert.ToInt32(ProductDropDownList.SelectedValue));


                    vendorPOItemEntity.ProductId = productEntity.Id;
                    vendorPOItemEntity.ProductName = productEntity.Name;
                    vendorPOItemEntity.ProductNo = productEntity.No;
                    vendorPOItemEntity.Rev = productEntity.Revision;
                    vendorPOItemEntity.RequestDate = Convert.ToDateTime(RequestDateTextBox.Text);
                    vendorPOItemEntity.RequestQty = Convert.ToInt32(QtyTextBox.Text);
                    vendorPOItemEntity.Lot = Convert.ToInt32(LotTextBox.Text);
                    vendorPOItemEntity.Price = Convert.ToDecimal(PriceTextBox.Text);
                    vendorPOItemEntity.Amount = vendorPOItemEntity.Price*vendorPOItemEntity.RequestQty;
                    vendorPOItemEntity.VendorId = Convert.ToInt32(SupplierDropDownList.SelectedValue);
                    vendorPOItemEntity.FormatDate = vendorPOItemEntity.RequestDate.ToString("d MMM, yyyy");
                    vendorPOItemEntity.ItemCategory = productEntity.CategoryName;
                    vendorPoItemEntities.Add(vendorPOItemEntity);
                }
                else
                {
                    Session["FlashMessage"] = "Error: No Product Selected!";
                    Session["FlashMessageType"] = "error";
                }

            }
            //create po item list session
            Session["VendorPoItemEntities"] = vendorPoItemEntities;
            VendorPOItemGridView.DataSource = Session["VendorPoItemEntities"] as IList<VendorPOItemEntity>;
            VendorPOItemGridView.DataBind();
            double totalAmount = 0;
            //foreach (VendorPOItemEntity v in vendorPoItemEntities)
            //{
            //    totalAmount += v.Amount;
            //}

            //TotalLabel.Text = totalAmount.ToString();


            foreach (GridViewRow r in VendorPOItemGridView.Rows)
            {
                TextBox qtyTextBox = (TextBox)r.Cells[4].FindControl("vQtyTextBox");
                TextBox priceTextBox = (TextBox)r.Cells[5].FindControl("vPriceTextBox");
                double qty = Convert.ToDouble(qtyTextBox.Text.Trim());
                double price = Convert.ToDouble(priceTextBox.Text.Trim());
                totalAmount = totalAmount + qty * price;
            }

            TotalLabel.Text = totalAmount.ToString() + " SGD";
        }

        protected int vendorPOId;
        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            VendorPOController vendorPoController = new VendorPOController();
            string newPONo = this.PONumberTextBox.Text.Trim();
            string msg = "";
            bool poNoAvailable = vendorPoController.CheckCustomerPONoAvailability(newPONo, ref msg);
            if (VendorPOItemGridView.Rows.Count > 0 && poNoAvailable)
            {
                
                VendorPOEntity vendorPoEntity = new VendorPOEntity();
                VendorPOItemController vendorPoItemController = new VendorPOItemController();
                vendorPoEntity.Address = ShipToTextBox1.Text + ", " + ShipToTextBox2.Text + ", " + ShipToTextBox3.Text;
                vendorPoEntity.ApprovedBy = 1;
                vendorPoEntity.Attention = "";
                vendorPoEntity.CreatedBy = 1;
                vendorPoEntity.VendId = int.Parse(SupplierDropDownList.SelectedValue);
                vendorPoEntity.Date = DateTime.Parse(PODateTextBox.Text);
                vendorPoEntity.Type = POTypeRadioButtonList.SelectedValue;
                vendorPoEntity.Fax = "";
                vendorPoEntity.No = PONumberTextBox.Text;
                vendorPoEntity.Phone = "";
                vendorPoEntity.Reference = ReferenceTextBox.Text;
                vendorPoEntity.Remark = RemarkTextBox.Text;
                vendorPoEntity.Status = "new";
                vendorPoEntity.ZipCode = ZipCodeTextBox.Text;
                vendorPoEntity.TotalQty = Convert.ToInt32(TotalQtyTextBox.Text);
                vendorPOId = vendorPoController.addVendorPO(vendorPoEntity);
                foreach (GridViewRow r in VendorPOItemGridView.Rows)
                {
                    //construct a vendor po item entity
                    VendorPOItemEntity vendorPoItemEntity = new VendorPOItemEntity();
                    vendorPoItemEntity.VendPoId = vendorPOId;
                    vendorPoItemEntity.Lot = Convert.ToInt32(((TextBox) r.FindControl("LotTextBox")).Text);
                    vendorPoItemEntity.Price = Convert.ToDecimal(((TextBox) r.FindControl("vPriceTextBox")).Text);
                    //vendorPoItemEntity.ProductId = int.Parse(r.Cells[7].Text);
                    vendorPoItemEntity.ProductId =
                        Convert.ToInt32(((HiddenField) r.FindControl("ProductIdHiddenField")).Value);
                    //HiddenField hiddenField = (HiddenField) r.FindControl("ProductIdHiddenField");
                    //string str = hiddenField.Value;
                    vendorPoItemEntity.ProductName = r.Cells[1].Text;
                    vendorPoItemEntity.ProductNo = r.Cells[0].Text;
                    vendorPoItemEntity.Remark = "";
                    vendorPoItemEntity.RequestDate =
                        Convert.ToDateTime(((TextBox) r.FindControl("vRequestDateTextBox")).Text);
                    vendorPoItemEntity.RequestQty = Convert.ToInt32(((TextBox) r.FindControl("vQtyTextBox")).Text);
                    vendorPoItemEntity.Status = "new";
                    vendorPoItemEntity.CompleteQty = 0;
                    
                    //insert this vendor po entity
                    vendorPoItemController.AddVendorPOItem(vendorPoItemEntity);


                }

                SettingController settingController = new SettingController();
                settingController.updateLargestVendorPONO();
                //Session["OrderEntities"] = null;
                // ClientScript.RegisterStartupScript(this.Page.GetType(), "Add Vendor PO Successful!", "alert('Add Vendor PO Successful!')", true);
                //SuccessfulLabel.Text = "Add Vendor PO Successful!";
                Session["FlashMessage"] = "Success: Add Vendor PO Successful!";
                Session["FlashMessageType"] = "success";
                IList<VendorPOItemEntity> vendorPoItemEntities1 =
                    Session["VendorPoItemEntities"] as IList<VendorPOItemEntity>;
                Session["PrepareToGeneratePDF"] = vendorPoItemEntities1;
                Session["VendorPOId"] = vendorPOId;
                Session["VendorPoItemEntities"] = null;
            }
            else
            {
                if (msg != "")
                {
                    Session["FlashMessage"] = msg;
                    Session["FlashMessageType"] = "error";
                }
                else
                {
                    Session["FlashMessage"] = "Error: No Item!";
                    Session["FlashMessageType"] = "error";
                }

            }
        }

        protected void ChooseSameDateCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (ChooseSameDateCheckBox.Checked)
            {
                TextBox dateTxt = new TextBox();

                foreach (GridViewRow r in VendorPOItemGridView.Rows)
                {
                    dateTxt = (TextBox)r.FindControl("vRequestDateTextBox");
                    string date = "";
                    if (dateTxt.Text.Length > 0)
                    {
                        date = dateTxt.Text;

                    }
                    dateTxt.Text = date;
                    break;
                }
                foreach (GridViewRow r in VendorPOItemGridView.Rows)
                {
                    if (dateTxt.Text.Length > 0)
                    {
                        ((TextBox)r.FindControl("vRequestDateTextBox")).Text = dateTxt.Text;
                    }
                }

            }
        }

        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            int rowIndex = ((GridViewRow)((Button)sender).NamingContainer).RowIndex;
            vendorPoItemEntities = Session["VendorPoItemEntities"] as IList<VendorPOItemEntity>;
            foreach (GridViewRow r in VendorPOItemGridView.Rows)
            {
                if (r.RowIndex == rowIndex)
                {

                    //HiddenField productIdlabel = (HiddenField)CustomerPOItemGridView.Rows[rowIndex].Cells[0].FindControl("ProductIdHiddenField");
                    //int productId = Convert.ToInt32(productIdlabel.Value);
                    if (vendorPoItemEntities != null)
                    {
                        for (int i = 0; i <= vendorPoItemEntities.Count; i++)
                        {
                            if (i == rowIndex)
                            {
                                vendorPoItemEntities.RemoveAt(i);
                            }

                        }
                    }
                }

            }
            Session["VendorPoItemEntities"] = vendorPoItemEntities;
            VendorPOItemGridView.DataSource = Session["VendorPoItemEntities"] as IList<VendorPOItemEntity>;
            VendorPOItemGridView.DataBind();
            decimal totalAmount = 0;
            foreach (VendorPOItemEntity v in vendorPoItemEntities)
            {
                totalAmount += v.Amount;
            }

            TotalLabel.Text = totalAmount.ToString();
        }

        //Generate vendor po pdf ******** Not Finished!*******
        protected void PDFButton_Click(object sender, EventArgs e)
        {
           IList<VendorPOItemEntity> vendorPoItemEntities = 
               Session["PrepareToGeneratePDF"] as IList<VendorPOItemEntity>;
            
            if(Session["PrepareToGeneratePDF"]!=null)
            {
                iTextSharp.text.Rectangle rec = new Rectangle(PageSize.A4); 
                
                iTextSharp.text.Document doc = new iTextSharp.text.Document(rec);

                string pdfName = "VendorPO_" + PONumberTextBox.Text + ".pdf";
                iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
                                                          new System.IO.FileStream(
                                                              Server.MapPath("./") + "PDF/" + pdfName,
                                                              System.IO.FileMode.Create));
                doc.SetMargins(15f, 15f, 15f, 15f);

                doc.Open();

                //Add an image object
                iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(Server.MapPath("logo.jpg"));
                iTextSharp.text.Table table = new iTextSharp.text.Table(11);
                table.BorderWidth = 0;
                //table.BorderColor = new Color(0, 0, 0);
                table.Padding = 1;
                table.Spacing = 1;

                Cell logo = new Cell(jpeg);
                logo.Header = true;
                logo.Colspan = 11;
                logo.HorizontalAlignment = 1;
                logo.Border = 0;
                table.AddCell(logo);

                Cell gst = new Cell("Co. & GST Registration Number: 20-0105271-M");
                gst.BackgroundColor = new Color(0xC0, 0xC0, 0xC0);
                gst.Colspan = 7;
                gst.HorizontalAlignment = 0;
                table.AddCell(gst);

                //Create a phrase that contain font style
                Phrase myPhrase = new Phrase("PURCHASE ORDER", FontFactory.GetFont(FontFactory.TIMES_BOLD, 14, Font.BOLD));
                Cell title = new Cell(myPhrase);
                title.BackgroundColor = new Color(0xC0, 0xC0, 0xC0);
                title.Colspan = 4;
                title.HorizontalAlignment = 1;
                table.AddCell(title);

                Cell vendor = new Cell("Vendor");
                vendor.Colspan = 7;
                vendor.HorizontalAlignment = 0;
                table.AddCell(vendor);


                Cell poinfo = new Cell();
                string poNo = this.PONumberTextBox.Text;
                string date = this.PODateTextBox.Text;
                Paragraph i1 = new Paragraph("PO No.: " + poNo);
                Paragraph i2 = new Paragraph("Date: " + date);
                Paragraph i3 = new Paragraph("Yr Quote: -");
                Paragraph i4 = new Paragraph("Terms: 30 days");
                Paragraph i5 = new Paragraph("Currency: SGD");
                poinfo.Add(i1);
                poinfo.Add(i2);
                poinfo.Add(i3);
                poinfo.Add(i4);
                poinfo.Add(i5);
                poinfo.Colspan = 4;
                poinfo.Rowspan = 6;
                table.AddCell(poinfo);

                Cell vendorInfo = new Cell();
                int vendorId = vendorPoItemEntities.ElementAt(0).VendorId;
                VendorController vendorController=new VendorController();
                VendorEntity vendorEntity = vendorController.findVendorByVendorId(vendorId);
                Paragraph p1 = new Paragraph("Vendor: " + vendorEntity.Name);
                Paragraph p2 = new Paragraph("Address: " + vendorEntity.Address);
                Paragraph p3 = new Paragraph("Attention: "+vendorEntity.ContactPerson);
                Paragraph p4 = new Paragraph("Postal Code: "+vendorEntity.ZipCode);
                Paragraph p5 = new Paragraph("Phone: "+vendorEntity.Phone);

                vendorInfo.Add(p1);
                vendorInfo.Add(p2);
                vendorInfo.Add(p3);
                vendorInfo.Add(p4);
                vendorInfo.Add(p5);


                vendorInfo.Colspan = 7;
                vendorInfo.Rowspan = 5;

                table.AddCell(vendorInfo);

                Cell qtyHeader = new Cell("Qty");
                qtyHeader.Colspan = 1;
                table.AddCell(qtyHeader);

                Cell noHeader=new Cell("No");
                noHeader.Colspan = 2;
                table.AddCell(noHeader);

                Cell nameHeader=new Cell("Description");
                nameHeader.Colspan = 2;
                table.AddCell(nameHeader);

                Cell revHeader = new Cell("Rev.");
                revHeader.Colspan = 1;
                table.AddCell(revHeader);

                Cell dateHeader=new Cell("Request Date");
                dateHeader.Colspan = 2;
                table.AddCell(dateHeader);

                Cell priceHeader=new Cell("Price");
                priceHeader.Colspan = 1;
                table.AddCell(priceHeader);

                Cell totalHeader=new Cell("TOTAL");
                totalHeader.Colspan = 2;
                table.AddCell(totalHeader);

                foreach (VendorPOItemEntity vendorPoItemEntity in vendorPoItemEntities)
                {
                    string no = vendorPoItemEntity.ProductNo;
                    //string name = vendorPoItemEntity.ProductName;
                    string name = vendorPoItemEntity.ItemCategory;
                    string rev = vendorPoItemEntity.Rev;
                    string qty = vendorPoItemEntity.RequestQty.ToString();
                    string requestDate = vendorPoItemEntity.RequestDate.ToString("d MMM, yyyy");
                    string price = vendorPoItemEntity.Price.ToString();
                    string total = (Convert.ToInt32(qty)*Convert.ToDecimal(price)).ToString();

                    Cell vqty = new Cell(qty);
                    vqty.Colspan = 1;
                    table.AddCell(vqty);
                    
                    Cell vno = new Cell(no);
                    vno.Colspan = 2;
                    table.AddCell(vno);

                    Cell vname = new Cell(name);
                    vname.Colspan = 2;
                    table.AddCell(vname);

                    Cell vrev = new Cell(rev);
                    vrev.Colspan = 1;
                    table.AddCell(vrev);

                    

                    Cell vdate = new Cell(requestDate);
                    vdate.Colspan = 2;
                    table.AddCell(vdate);

                    Cell vprice = new Cell("S$"+price);
                    vprice.Colspan = 1;
                    table.AddCell(vprice);

                    Cell vtotal = new Cell("S$" + total);
                    vtotal.Colspan = 2;
                    table.AddCell(vtotal);
                    
                }
                
                VendorPOController vendorPoController = new VendorPOController();
                int vendorPOId = Convert.ToInt32(Session["VendorPOId"]);
                VendorPOEntity vendorPoEntity = vendorPoController.findVendorPOById(vendorPOId);

                Cell remark=new Cell();
                remark.Colspan = 6;
                remark.Rowspan = 3;
                Paragraph rp=new Paragraph("Special Instructions");
                Paragraph rp1=new Paragraph(this.RemarkTextBox.Text);
                remark.Add(rp);
                remark.Add(rp1);
                table.AddCell(remark);

                Cell amountSumary =new Cell();
                amountSumary.Colspan = 5;
                amountSumary.Rowspan = 3;
                amountSumary.HorizontalAlignment = 2;
                decimal subTotal = 0;
                foreach (VendorPOItemEntity vendorPoItemEntity in vendorPoItemEntities)
                {
                    subTotal += vendorPoItemEntity.Amount;
                }
                double gstvalue = (double) subTotal*0.07;
                double totalvalue = (double)subTotal + gstvalue;
                Paragraph ap1=new Paragraph("Sub Total: S$"+subTotal);
                Paragraph ap2=new Paragraph("GST: S$"+gstvalue);
                Paragraph ap3 = new Paragraph("TOTAL: S$" + totalvalue);

                amountSumary.Add(ap1);
                amountSumary.Add(ap2);
                amountSumary.Add(ap3);
                table.AddCell(amountSumary);


                Cell shippingAddress=new Cell();
                shippingAddress.Colspan = 6;
                shippingAddress.Rowspan = 3;
                Paragraph sp1=new Paragraph("Shipping Address");
                Paragraph sp2=new Paragraph(vendorPoEntity.Address);
                Paragraph sp4 = new Paragraph("SINGAPORE "+vendorPoEntity.ZipCode);
                Paragraph sp3=new Paragraph(vendorPoEntity.Attention);

                shippingAddress.Add(sp1);
                shippingAddress.Add(sp2);
                shippingAddress.Add(sp4);
                shippingAddress.Add(sp3);

                table.AddCell(shippingAddress);

                Cell officeUse=new Cell("Office Use Only");
                officeUse.Colspan = 5;
                officeUse.Rowspan = 4;
                table.AddCell(officeUse);
                doc.Add(table);
                doc.Close();
                Response.Redirect("PDF/" + pdfName);
               
            }
            else
            {
                //SuccessfulLabel.Text = "Please submit vendor PO first.";
                Session["FlashMessage"] = "Error: Please Submit Vendor PO First!";
                Session["FlashMessageType"] = "error";
            }


        }

        

        

        
    }
}